#!/usr/bin/Rscript

path = "/home/acvmarsh/public_html/inflow/"
path = "./"
outfile = paste(path,'inflow',sep='')
tmpfile = paste(path,'TEMP',sep='')
    
usefourier = F  #If this parameter is T then weight the fourer model 
                #and the stl model based on the standard error
                #-- this is tpically worse than using just stl

    #load the parameter file
load(paste(path,'parms.RData',sep=''))

    #load the most recent rainfall data
rf = read.table(paste(path,'rainfall',sep=""),fill=TRUE,header=TRUE)
rf[nrow(rf),3] <- rf[nrow(rf),2]
	
    #sum the rainfall over the last 4 days
collect = 4
rf = sum(rf[(nrow(rf)-collect+1):nrow(rf),3])


theday = as.integer(system("date +%j",intern=T))
year = as.integer(system("date +%Y",intern=T))

    #check if it is a leap year and if the date is later than Feb 28
if( (year %% 4) == 0 & theday > (30+28)){
    theday = theday - 1
}

pred <- numeric(length(models))
for(i in 1:length(models)){
    pred[i] <- rf - rper[[i]][theday] - rave[[i]]
    pred[i] <- a[[i]] + b[[i]] * pred[i]
    pred[i] <- pred[i] + iave[[i]] + iper[[i]][theday]
}
if(usefourier){
    W <- sapply(se,mean)
    W <- W/sum(W)
}else{
    pred <- pred[1]
    W <- c(1,0)
}

pred <- sum(W*pred)
se <- sum(W*sapply(se,mean))

upper = pred + z * se
lower = pred - z * se

date = Sys.Date()

    #count the number of lines in the file and 
    #read in the last two lines in the file 
n = as.integer(system(paste('wc -l <',outfile),intern=T))
lastTwo = scan(outfile,what="character",sep="@",skip=(n-2),quiet=T)

yesterday = c(as.character(date-1))
today = c(as.character(date),round(c(pred,upper,lower),4))

inthere = grep(today[1],lastTwo)
p <- sprintf("%s %6.4f %6.4f %6.4f",today[1],today[2],today[3],today[4])
if(length(inthere)==0){
    #then today's data has not been added
    bad = grep(yesterday,lastTwo)
    if(length(bad)>0){
        #Remove the last line in the file (the old forecasted value) and print the two 
        #new values (yesterday's observed and today's forecast)
        cat(p,'\n',file=outfile,append=T)
        cat('Added todays inflow forecast.\n')
    }else{
        cat(p,'\n',file=outfile,append=T)
        cat('Yesterday value was not in the file, but todays was.\n')
        cat('There may be holes in the data.\n')
        cat('Added todays forecasted inflow.\n')
    }

}else{
    #remove the last two lines in the file with the current values
    #though they are likely the same
    system(paste('grep -v',today[1],outfile,'>',tmpfile))
    system(paste('cat',tmpfile,'>',outfile))
    cat(p,'\n',file=outfile,append=T)
    cat('Todays value was already in the file but it was replaced anyway.\n')
    
}

if(file.exists(tmpfile)) dummy = file.remove(tmpfile)
